package com.kobe.classification.service.Impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.kobe.classification.domain.ClassificationDomain;
import com.kobe.classification.mapper.ClassificationMapper;
import com.kobe.classification.service.ClassificationService;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Mapper
public class ClassificationServiceImpl implements ClassificationService {

    @Autowired
    private ClassificationMapper classificationMapper;


    @Override
    public List<Tree<String>> treeV3() {
        long begin = System.currentTimeMillis();
        // 查询全部数据
        List<ClassificationDomain> nodeList = classificationMapper.selectAll();

        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setIdKey("categoryId");
        treeNodeConfig.setWeightKey("categoryId");

        List<Tree<String>> treeNodes = TreeUtil.build(nodeList, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getCategoryId().toString());
                    // 修复空指针异常：安全地处理 parentId 为 null 的情况
                    tree.setParentId(treeNode.getParentId() != null ? treeNode.getParentId().toString() : "0");
                    // 权重默认是0，这里根据orderNum排序，orderNum越小，权重越大
                    // 扩展属性 ...
                    //分类名称
                    tree.putExtra("categoryName", treeNode.getCategoryName());
                    //备注
                    tree.putExtra("remark", treeNode.getRemark());
                    //创建人
                    tree.putExtra("createBy", treeNode.getCreateBy());
                    //创建时间
                    tree.putExtra("createTime", treeNode.getCreateTime());
                    //状态
                    tree.putExtra("status", treeNode.getStatus());
                });
        long end = System.currentTimeMillis();
        System.out.println("查询耗时: " + (end - begin) + " ms");
        return treeNodes;
    }

    @Override
    public int insert(ClassificationDomain classificationDomain) {
        return classificationMapper.insert(classificationDomain);
    }

    @Override
    public int update(ClassificationDomain classificationDomain) {
        return classificationMapper.update(classificationDomain);
    }

    @Override
    public ClassificationDomain selectById(Long categoryId) {
        return classificationMapper.selectById(categoryId);
    }
}